package artid.com.arttogo.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.android.volley.VolleyError;
import com.bumptech.glide.Glide;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.AucOrgDetAucListAdapter;
import artid.com.arttogo.adapter.AuctionComment_Adapter;
import artid.com.arttogo.bean.AuctionAuctionListParser;
import artid.com.arttogo.bean.AuctionCommentParser;
import artid.com.arttogo.bean.JigouInfo;
import artid.com.arttogo.bean.OneStateIntParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.AlertUtils;
import artid.com.arttogo.utils.GlideUtil;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.CircleImageView;
import artid.com.arttogo.view.MyEditText;
import artid.com.arttogo.view.MyListView;

/**
 * 项目名称：ArtworkArt 类名称：AucOrgDetActivity 类描述： 机构详情
 */
public class AucOrgDetActivity extends BaseActivity implements OnClickListener, OnTouchListener {

    /**********
     * DECLARES
     *************/
    private ImageView auc_org_det_img;
    private TextView auc_org_det_name;
    private TextView auc_org_det_money;
    private TextView auc_org_det_site;
    private TextView auc_org_det_tel;
    private ImageView auc_org_det_tel_icon;
    private TextView auc_org_det_info;
    //	private TextView auc_org_det_his_deal;
//	private TextView auc_org_det_deal_rate;
    private View  auc_org_det_his_info;
    private MyListView auc_org_det_his_list;

    private MyListView auc_org_det_cmt_list;
    private TextView auc_org_det_more;
    private TextView lot_det_cmt;
    View cmt_view, cmt_view2, cmt_tag;
    View hideCmt;
    private List<AuctionCommentParser> list = new ArrayList<AuctionCommentParser>();
    private List<AuctionCommentParser> more_list = new ArrayList<AuctionCommentParser>();
    AucOrgDetAucListAdapter mAdapter;
    AuctionComment_Adapter mCmtAdapter;
    String id;
    int page = 1;
    private MyEditText replyEd;
    private TextView sendBtn;
    private RatingBar mRatingBar;
    private LinearLayout ratingBarLL;
    private RelativeLayout allroot;
    private int score;// 发表评论-评分
    private int replyPosition = -1;// -1的时候为评论反之都是评论
    private String replyID;// 回复ID
    ScrollView mScroll;
    /**
     * 展开箭头
     */
    private ImageView head_downBtn;

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private String imgwide;// 请求的图片宽度
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        mContext = AucOrgDetActivity.this;
        setContentView(R.layout.activity_auc_org_det);
        initView();
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    private void initView() {
        mContext = AucOrgDetActivity.this;
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 1) + "";
        IntentFilter filter = new IntentFilter("com.AucOrgDetActivity.receiver");
        registerReceiver(broadcastReceiver, filter);
        mTittle = (TextView) findViewById(R.id.tittle_text);
        mTittle.setText("机构详情");
        mBack = (ImageView) findViewById(R.id.back_btn);
        mBack.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        ImageView mViewMore = (ImageView) findViewById(R.id.share_collection_detail);
        mViewMore.setImageResource(R.drawable.jg_xq_share);
        mViewMore.setVisibility(View.VISIBLE);
        mViewMore.setOnClickListener(this);
        /********** INITIALIZES *************/
        // 评论
        mScroll = (ScrollView) findViewById(R.id.auc_scroll);
        mScroll.smoothScrollTo(0, 20);
        replyEd = (MyEditText) findViewById(R.id.AuctionComment_replyEd2);
        head_downBtn = (ImageView) findViewById(R.id.celebritysealinfo_head_down);
        replyEd.setOnEditorActionListener(onEditorAction);
        replyEd.setHint("123");
        sendBtn = (TextView) findViewById(R.id.AuctionComment_sendBtn);
        sendBtn.setOnClickListener(this);
        ratingBarLL = (LinearLayout) findViewById(R.id.AuctionComment_ratingBarLL);
        ratingBarLL.setVisibility(View.GONE);
        mRatingBar = (RatingBar) findViewById(R.id.AuctionComment_ratingBar);
        mRatingBar.setOnRatingBarChangeListener(onRatingBar);
        cmt_tag = (View) findViewById(R.id.org_det_cmt_tag);
        cmt_tag.setOnClickListener(this);
        cmt_view = (View) findViewById(R.id.cmt_view);
        cmt_view2 = (View) findViewById(R.id.cmt_view2);
        hideCmt = (View) findViewById(R.id.auc_org_hide);
        hideCmt.setOnClickListener(this);
        allroot = (RelativeLayout) findViewById(R.id.root);
        allroot.setOnTouchListener(this);
        head_downBtn.setOnClickListener(this);
        auc_org_det_cmt_list = (MyListView) findViewById(R.id.auc_org_det_cmt_list);
        auc_org_det_more = (TextView) findViewById(R.id.auc_org_det_more);
        auc_org_det_more.setOnClickListener(this);
        lot_det_cmt = (TextView) findViewById(R.id.lot_det_cmt);

        auc_org_det_img = (ImageView) findViewById(R.id.auc_org_det_img);
        auc_org_det_name = (TextView) findViewById(R.id.auc_org_det_name);
        auc_org_det_money = (TextView) findViewById(R.id.auc_org_det_money);
        auc_org_det_site = (TextView) findViewById(R.id.auc_org_det_site);
        auc_org_det_tel = (TextView) findViewById(R.id.auc_org_det_tel);
        auc_org_det_tel_icon = (ImageView) findViewById(R.id.auc_org_det_tel_icon);
        auc_org_det_info = (TextView) findViewById(R.id.auc_org_det_info);
//		auc_org_det_his_deal = (TextView) findViewById(R.id.auc_org_det_his_deal);
//		auc_org_det_deal_rate = (TextView) findViewById(R.id.auc_org_det_deal_rate);
        auc_org_det_his_info = (TextView) findViewById(R.id.auc_all);
        auc_org_det_his_info.setOnClickListener(this);

        auc_org_det_his_list = (MyListView) findViewById(R.id.auc_org_det_his_list);

        id = getIntent().getExtras().getString("id");
        getData();
        getAucListData();
        getCmtData();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.share_collection_detail:
                //分享
                if (item != null) {
                    AppUtil.shareAuction(mContext, "1", item.getSeller_name(), item.getMemo(), item.getLogo(),
                            item.getShareurl() + "&type=1", item.getId(), false);
                }
                break;
            case R.id.auc_org_det_more:
                page++;
                getCmtData();
                break;
            case R.id.org_det_cmt_tag:

                startComment("");

                break;
            case R.id.auc_org_hide:
                if (cmt_view.getVisibility() == View.VISIBLE) {
                    hideKeyBoard();
                    ratingBarLL.setVisibility(View.GONE);
                    cmt_view.setVisibility(View.GONE);
                    cmt_view2.setVisibility(View.GONE);
                    hideCmt.setVisibility(View.GONE);
                }
                break;

            case R.id.AuctionComment_sendBtn:
                // 发送信息
                if (!TextUtils.isEmpty(replyEd.getText().toString().trim())) {
                    if (replyPosition == -1) {
                        sendComment();
                    } else {
                        replyComment();
                    }
                } else {
                    ToastUtil.toast(mContext, "评论不能为空");
                }
                break;
            case R.id.auc_all:
                Intent intent = new Intent(mContext, AuctionAll_Activity.class);
                intent.putExtra("organizationID", id);
                startActivity(intent);
                break;
            case R.id.celebritysealinfo_head_down: {
                if (mState == SPREAD_STATE) {
                    auc_org_det_info.setMaxLines(VIDEO_CONTENT_DESC_MAX_LINE);
                    auc_org_det_info.requestLayout();
                    head_downBtn.setImageResource(R.drawable.jg_xq_zhankai);
                    mState = SHRINK_UP_STATE;
                } else if (mState == SHRINK_UP_STATE) {//
                    auc_org_det_info.setMaxLines(Integer.MAX_VALUE);
                    auc_org_det_info.requestLayout();
                    head_downBtn.setImageResource(R.drawable.jg_xq_hebing);
                    mState = SPREAD_STATE;
                }
                break;
            }
            default:
                break;
        }
    }

    // OnItemClickListener onItemClick=new OnItemClickListener() {
    //
    // @Override
    // public void onItemClick(AdapterView<?> arg0, View arg1, int position,
    // long arg3) {
    // // TODO Auto-generated method stub
    // Intent intent = new Intent(mContext,CollecterActivity.class);
    // intent.putExtra("id",more_list.get(position).getArtist_id());
    // mContext.startActivity(intent);
    // }d an
    // };
    JigouInfo item;

    private void getData() {
        VolleyBasic.getInstance(this).post(Cache.jigouInfo,
                VolleyMap.getInstance().jigouInfo(id), JigouInfo.class,
                new VolleyCallback() {
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        item = (JigouInfo) vd.getData();
                        GlideUtil.setImage1(mContext, item.getLogo()
                                + "_"
                                + (Integer.parseInt(NetUtils
                                .getDisplayMetrics(
                                        (Activity) mContext)
                                .get(NetUtils.DM_WIDTH)) / 2)
                                + "x10.png", R.drawable.ic_menu_rotate, R.drawable.ic_menu_rotate, auc_org_det_img);
//                        Glide.with(mContext)
//                                .load(item.getLogo()
//                                        + "_"
//                                        + (Integer.parseInt(NetUtils
//                                        .getDisplayMetrics(
//                                                (Activity) mContext)
//                                        .get(NetUtils.DM_WIDTH)) / 2)
//                                        + "x10.png")
//                                .asBitmap()
//                                .centerCrop()
//                                .placeholder(R.drawable.ic_menu_rotate)
//                                .error(R.drawable.ic_menu_rotate)
//                                .into(new MyBitmapImageViewTarget(
//                                        auc_org_det_img));
                        auc_org_det_name.setText(item.getSeller_name());
                        auc_org_det_money.setText(item.getCommission());
                        auc_org_det_site.setText(item.getAddress());
                        auc_org_det_tel.setText(item.getPhone());
                        auc_org_det_tel_icon
                                .setOnClickListener(new OnClickListener() {

                                    @Override
                                    public void onClick(View arg0) {
                                        // TODO Auto-generated method stub
                                        AlertUtils.phoneAlertDialog(AucOrgDetActivity.this, item.getPhone(), new OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Intent intent = new Intent(
                                                        Intent.ACTION_CALL);
                                                Uri data = Uri.parse("tel:"
                                                        + item.getPhone());
                                                intent.setData(data);
                                                if (ActivityCompat.checkSelfPermission(AucOrgDetActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                                    // TODO: Consider calling
                                                    //    ActivityCompat#requestPermissions
                                                    // here to request the missing permissions, and then overriding
                                                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                                    //                                          int[] grantResults)
                                                    // to handle the case where the user grants the permission. See the documentation
                                                    // for ActivityCompat#requestPermissions for more details.
                                                    return;
                                                }
                                                startActivity(intent);
                                            }
                                        });

                                    }
                                });
                        setTextViewText(auc_org_det_info, item.getMemo());
//						auc_org_det_his_deal.setText(item.getUnit()
//								+ item.getTurnover());
//						auc_org_det_deal_rate.setText(item.getTurnoverrate());
                        // mTextArtistCate.setText(item.getLot_author()+"/"+item.getLot_age()+"/"
                        // item.getLot_class());
                        // mTextSize.setText(item.getLot_size()+"/"+item.getLot_mounting());
                        // mTextSeal.setText(item.getLot_recording());
                        // mTextLogo.setText(item.getLot_material());
                        // mTextInfo.setText(item.getLot_memo());
                        mScroll.scrollTo(0, 0);
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    private void getAucListData() {
        VolleyBasic.getInstance(this).post(Cache.auction_auctionList,
                VolleyMap.getInstance().auction_auctionList(1, 3, id, "1",imgwide),
                AuctionAuctionListParser.class, new VolleyCallback() {

                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub

                        final List<AuctionAuctionListParser> list = (List<AuctionAuctionListParser>) vd
                                .getList();
                        mAdapter = new AucOrgDetAucListAdapter(mContext, list);
                        auc_org_det_his_list.setAdapter(mAdapter);
                        auc_org_det_his_list
                                .setOnItemClickListener(new OnItemClickListener() {

                                    @Override
                                    public void onItemClick(
                                            AdapterView<?> arg0, View arg1,
                                            int arg2, long arg3) {
                                        // TODO Auto-generated method stub
                                        Intent intent = new Intent(mContext,
                                                AuctionInfo_Activity.class);
                                        intent.putExtra("auctionID",
                                                list.get(arg2).getId());
                                        intent.putExtra("SpecialListData", 0);
                                        startActivity(intent);
                                    }
                                });

                        mAdapter.notifyDataSetChanged();
                        mTittle.requestFocus();
                        mScroll.fullScroll(ScrollView.FOCUS_UP);
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    private void getCmtData() {
        VolleyBasic.getInstance(this).post(Cache.jgcommentList,
                VolleyMap.getInstance().jigou_commentList(page, 10, id, "1"),
                AuctionCommentParser.class, new VolleyCallback() {

                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub

                        list = (List<AuctionCommentParser>) vd.getList();
                        if(more_list!=null){
                            //因为现在可以回复自己所以必须清空列表
                            more_list.clear();
                        }
                        if (!list.isEmpty()) {
                            more_list.addAll(list);
                        }
                        lot_det_cmt.setText("说说这个机构(" + more_list.size() + ")");
                        if (mCmtAdapter == null) {
                            mCmtAdapter = new AuctionComment_Adapter(mContext,"1", more_list);
                            auc_org_det_cmt_list.setAdapter(mCmtAdapter);
                        }
                        mCmtAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     * 星级评论监听
     */
    OnRatingBarChangeListener onRatingBar = new OnRatingBarChangeListener() {

        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating,
                                    boolean fromUser) {
            // TODO Auto-generated method stub
            score = (int) rating;
        }
    };

    /**
     * 软键盘回车按钮的监听
     */
    OnEditorActionListener onEditorAction = new OnEditorActionListener() {

        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            final String searchStr = replyEd.getText().toString().trim();
            if (actionId == EditorInfo.IME_ACTION_SEARCH
                    || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                // do something;
                if (searchStr == null || "".equals(searchStr)) {
                    ToastUtil.toast(mContext, "您似乎忘了点什么");
                    return true;
                } else {
                    if (replyPosition == -1) {
                        sendComment();
                    } else {
                        replyComment();
                    }
                }
                return false;
            }
            return false;
        }
    };
    // /**
    // * 关闭软键盘
    // * @param mContext
    // */
    // public void hideKeyboard(Context mContext){
    // InputMethodManager imm = (InputMethodManager)
    // mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
    // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    // }



    /**
     * 发表评论 机构id id 也可以是拍卖会id,专场id,拍品id 评论类型 type 1,机构，2，拍卖会，3专场，4拍品 评论内容
     * content 评分 score 1-5分
     */
    private void sendComment() {
        VolleyBasic.getInstance(this).post(
                Cache.replyComment,
                VolleyMap.getInstance().replyComment(id, "1",
                        replyEd.getText().toString(), score),
                OneStateIntParser.class, new VolleyCallback() {

                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        OneStateIntParser bean = (OneStateIntParser) vd
                                .getData();
                        if (bean.getState() == 1) {
                            ToastUtil.toast(mContext, "发送成功");
                            replyEd.setText("");
                            mRatingBar.setRating(0);
                            page = 1;

                            VolleyBasic
                                    .getInstanceNoDialog((Activity) mContext);
                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    getCmtData();
                                }
                            }, 1000);

                        } else {
                            ToastUtil.toast(mContext, "发送失败");
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        ToastUtil.toast(mContext, "发送失败");
                    }
                });
    }

    /**
     * 回复评论 id id 机构/拍卖会/专场/拍品的id 用户口令 token 内容 content 回复那条评论的id commentid 类型
     * type 1,机构，2，拍卖会，3专场，4拍品 评分 score 评分范围0-5
     */
    private void replyComment() {
        VolleyBasic.getInstance(this).post(
                Cache.Answercomment,
                VolleyMap.getInstance().Answercomment(id, "1", replyID,
                        replyEd.getText().toString(), score),
                OneStateIntParser.class, new VolleyCallback() {

                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        OneStateIntParser bean = (OneStateIntParser) vd
                                .getData();
                        if (bean.getState() == 1) {
                            ToastUtil.toast(mContext, "发送成功");
                            replyPosition = -1;// 恢复状态
                            replyEd.setText("");
                            replyEd.setHint("评论:");
                            mRatingBar.setRating(0);
                            page = 1;

                            VolleyBasic
                                    .getInstanceNoDialog(AucOrgDetActivity.this);
                            // getData();
                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    // TODO Auto-generated method stub
                                    getCmtData();
                                }
                            }, 1000);
                        } else {
                            ToastUtil.toast(mContext, "发送失败");
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        ToastUtil.toast(mContext, "发送失败");
                    }
                });
    }



    void startComment(String strPreFix) {
        ratingBarLL.setVisibility(View.VISIBLE);
        cmt_view.setVisibility(View.VISIBLE);
        cmt_view2.setVisibility(View.VISIBLE);
        hideCmt.setVisibility(View.VISIBLE);
        replyEd.setHint(strPreFix);
        replyEd.setFocusable(true);
        InputMethodManager imm = (InputMethodManager) replyEd.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
        // mscroll.fullScroll(ScrollView.FOCUS_DOWN);
        hideCmt.setVisibility(View.VISIBLE);
        replyEd.requestFocus();

    }

    void hideKeyBoard() {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService("input_method");
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView()
                    .getWindowToken(), 0);
        }
        hideCmt.setVisibility(View.GONE);
        replyPosition = -1;// 恢复状态
        replyEd.setHint("");
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("AucOrgDet Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        AppIndex.AppIndexApi.start(client, getIndexApiAction());
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        AppIndex.AppIndexApi.end(client, getIndexApiAction());
        client.disconnect();
    }

    //超过三行折叠
    public static final String MainActivity = "MainActivity";
    private static final int VIDEO_CONTENT_DESC_MAX_LINE = 3;
    private static final int SHRINK_UP_STATE = 1;
    private static final int SPREAD_STATE = 2;
    private static int mState = SHRINK_UP_STATE;

    private void setTextViewText(TextView mContentText, String content) {
        mContentText.setText(content);
        mContentText.post(new StrecthRunnable(mContentText));
    }

    class StrecthRunnable implements Runnable {

        private TextView tvStrecth;

        public StrecthRunnable(TextView tvStrecth) {
            this.tvStrecth = tvStrecth;
        }

        public void run() {
            if (isStrecthShrink(tvStrecth)) {
                tvStrecth.setMaxLines(VIDEO_CONTENT_DESC_MAX_LINE);
                tvStrecth.setEllipsize(TextUtils.TruncateAt.END);
                head_downBtn.setVisibility(View.VISIBLE);
                head_downBtn.setImageResource(R.drawable.jg_xq_zhankai);
            } else {
                head_downBtn.setVisibility(View.GONE);
            }
        }

    }

    private boolean isStrecthShrink(TextView mContentText) {
        int lines = mContentText.getLineCount();
        Log.d(MainActivity, "lines =" + lines);
        if (lines > VIDEO_CONTENT_DESC_MAX_LINE) {//
            return true;
        } else {
            return false;
        }
    }

    /**
     * 滑动返回上级
     */
    //手指向右滑动时的最小速度
    private static final int XSPEED_MIN = 200;

    //手指向右滑动时的最小距离
    private static final int XDISTANCE_MIN = 150;

    //记录手指按下时的横坐标。
    private float xDown;

    //记录手指移动时的横坐标。
    private float xMove;

    //用于计算手指滑动的速度。
    private VelocityTracker mVelocityTracker;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        createVelocityTracker(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDown = event.getRawX();
                Log.e("xDown", event.getRawX() + "");
                break;
            case MotionEvent.ACTION_MOVE:
                xMove = event.getRawX();
                Log.e("xMove", event.getRawX() + "");
                //活动的距离
                int distanceX = (int) (xMove - xDown);
                //获取顺时速度
                int xSpeed = getScrollVelocity();
                //当滑动的距离大于我们设定的最小距离且滑动的瞬间速度大于我们设定的速度时，返回到上一个activity
                if (distanceX > XDISTANCE_MIN && xSpeed > XSPEED_MIN) {
                    finish();
                    //设置切换动画，从右边进入，左边退出
                    overridePendingTransition(R.anim.in_from_left, R.anim.out_to_right);
                }
                break;
            case MotionEvent.ACTION_UP:
                recycleVelocityTracker();
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 创建VelocityTracker对象，并将触摸content界面的滑动事件加入到VelocityTracker当中。
     *
     * @param event
     */
    private void createVelocityTracker(MotionEvent event) {
        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(event);
    }

    /**
     * 回收VelocityTracker对象。
     */
    private void recycleVelocityTracker() {
        mVelocityTracker.recycle();
        mVelocityTracker = null;
    }

    /**
     * 获取手指在content界面滑动的速度。
     *
     * @return 滑动速度，以每秒钟移动了多少像素值为单位。
     */
    private int getScrollVelocity() {
        mVelocityTracker.computeCurrentVelocity(1000);
        int velocity = (int) mVelocityTracker.getXVelocity();
        return Math.abs(velocity);
    }

    //广播接收器
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getBooleanExtra("isReply", false)) {
                //判断是否为适配器发送的回复推送
                int position=intent.getIntExtra("Position",-1);
                if(position!=-1) {
                    if (!TextUtils.isEmpty(AppUtil.getUser().getUid())) {
                        replyPosition = position;
                        startComment("");
                        replyEd.setHint("@" + more_list.get(position).getRealname());
                        replyID = more_list.get(position).getMessid();
                    } else {
                        AppUtil.Logout(mContext);
                        AppUtil.LoginVer(mContext);
                    }
                }
            };
        }
    };

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 关闭广播
        unregisterReceiver(broadcastReceiver);
    }
}
